<template>
  <div>
    <div v-if="!addOrUpdateDialogVisible"   class="mod-config" id="mod-config-id">
      <div v-if="isAuth('ent:role:paging')" class="div-s" id="div-s-id">
        <el-form :model="params" :label-position="labelPosition" ref="queryFormRef" :inline="true" label-width="70px" class="queryFormed">
          <el-row class="row-s">
            <el-col :span="6">
              <el-form-item label="角色名称" prop="name">
                <el-input v-model="params.name" placeholder="请输入角色名称" @clear="clearName" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col class="col-right" :span="6" :offset="12">
              <el-form-item class="item-all">
                <el-button class="buttonItem" size="mini" plain @click="clickReset()">重 置</el-button>
                <el-button class="buttonItem" size="mini" type="primary" @click="clickSearch()">搜 索</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="div-e" id="div-e-id">
        <div class="div-inquire" id="div-inquire-id">
          <div class="in-t">
            <div class="in-ts"></div>
            <h3 >角色管理</h3>
          </div>
          <div v-if="!inqerts" class="div-button">
            <el-button v-if="isAuth('ent:role:save')" size="mini" type="primary" icon="el-icon-plus" @click="showAddOrUpdateDialog(true)">新增</el-button>
            <el-button v-if="isAuth('ent:role:delete')" size="mini" type="danger" icon="el-icon-delete" @click="clickDeleteBatch" :disabled="this.tableSelection.length < 1">批量删除</el-button>
          </div>
        </div>
        <el-table
          ref="multipleTable"
          :data="tableData"
          :max-height="table.tableHeight"
          :header-cell-style="{background:'#F5F7FA'}"
          style="width: 100%"
          v-loading="dataListLoading"
          @selection-change="handleSelectionChange"
          fit>
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column
            label="角色名称"
            width="200"
            prop="name"
            align="center">

          </el-table-column>
          <el-table-column
            prop="parentName"
            label="上级角色"
            width="200"
            align="center">
          </el-table-column>
          <el-table-column
            prop=""
            label="是否为管理层"
            width="200"
            align="center">
            <template slot-scope="scope">
              {{scope.row.managerFlag === 0 ? '否' : '是'}}
            </template>
          </el-table-column>
          <el-table-column
            prop=""
            label="是否区域管理人"
            width="200"
            align="center">
            <template slot-scope="scope">
              {{scope.row.areaManagerFlag === 0 ? '否' : '是'}}
            </template>
          </el-table-column>
          <el-table-column
            prop="remark"
            label="备注"
            align="center">
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="创建时间"
            width="200"
            align="center">
          </el-table-column>
          <el-table-column
            label="操作"
            align="center">
            <template slot-scope="scope">
              <el-button v-if="isAuth('ent:role:update')" type="text" size="mini" class="btn-text-normal" @click="showAddOrUpdateDialog(false,scope.row.id)">修改</el-button>
              <el-button v-if="isAuth('ent:role:delete')" type="text" size="mini" class="btn-text-danger" @click="clickDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="changePageSize"
          @current-change="turnToPage"
          :current-page="queryInfo.pageIndex"
          :page-sizes="[5, 10, 20, 50, 100, 200]"
          :page-size="queryInfo.pageSize "
          layout="total, prev, pager, next, sizes, jumper"
          :total="totalPage"
          id="div-e-paging-id">
        </el-pagination>
      </div>

<!--      <function-authorization @changeMenuIdList="getMenuIdList" :isUpdatable="false"></function-authorization>
      <data-authorization @changeDataIdList="getDataIdList" :tree-props="deptTreeProps" :tree-list="deptTreeList" :default-checked-id-list="roleForm.deptIdList" ></data-authorization>-->
    </div>
    <authorization-form v-show="addOrUpdateDialogVisible">
      <template slot="head">
        <div class="div-s" >
          <el-form :model="roleForm" :rules="roleFormRules" ref="roleFormRefs"    label-width="100px" class="queryFormed">
            <el-row class="">
              <el-col :span="11">
                <el-form-item label="角色名称" prop="name" >
                  <el-input v-model="roleForm.name" placeholder="请输入角色名称" style="width: 100%"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="11" :offset="1">
                <el-form-item label="上级角色" clearable>
                  <el-select v-model="roleForm.parentId" placeholder="请选择上级角色" style="width: 100%">
                    <el-option
                      v-for="item in tableData"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="11">
                <el-form-item label="是否为管理层" prop="managerFlag">
                  <el-radio-group v-model="roleForm.managerFlag">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                  </el-radio-group>
                  <span v-if="roleForm.managerFlag" style="color:#999999;font-size: 12px;">显示该人员所在部门以及下级部门的数据</span>
                  <span v-if="!roleForm.managerFlag" style="color:#999999;font-size: 12px;">只显示该人员的数据</span>
                </el-form-item>
              </el-col>
              <el-col :span="11" :offset="1">
                <el-form-item label="是否区域管理" prop="areaManagerFlag">
                  <el-radio-group v-model="roleForm.areaManagerFlag">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="11">
                <el-form-item label="备注" >
                  <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" v-model="roleForm.remark" placeholder="备注" style="width: 100%"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </template>
      <template slot=left><function-authorization ref="funcAuthRefs" :is-updatable='true'   :default-checked-menu-id-list="roleForm.menuIdList"></function-authorization></template>
      <template slot=right><data-authorization  ref="dataAuthRefs" :is-updatable='true'   :tree-props="deptTreeProps" :default-checked-id-list="roleForm.deptIdList"></data-authorization></template>
      <template slot=bottom>
        <div style="display: flex;justify-content: center">
          <el-button @click="addOrUpdateDialogVisible = false">返 回</el-button>
          <el-button type="primary" @click="clickConfirm">保 存</el-button>
        </div>
      </template>
    </authorization-form>
<!--    <el-dialog
      title=""
      :visible.sync="addOrUpdateDialogVisible"
      width="45%">
      <span slot="title">{{isAddRole?"角色新增":"角色修改"}}</span>
      <div >
        <el-form :model="roleForm" :rules="roleFormRules" ref="roleFormRefs"  label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" placeholder="角色名称"></el-input>
          </el-form-item>
          <el-form-item label="上级角色" clearable>
            <el-select v-model="roleForm.parentId" placeholder="请选择上级角色">
              <el-option
                v-for="item in tableData"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否为管理层" prop="managerFlag">
            <el-radio-group v-model="roleForm.managerFlag">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注" >
            <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" v-model="roleForm.remark" placeholder="备注"></el-input>
          </el-form-item>
          <el-row>
            <el-col :span="11">
              <el-form-item label="功能授权" prop="menuIdList">
              <el-tree :data="funcTreeList"
                       :props="funcTreeProps"
                       :default-checked-keys="roleForm.menuIdList"
                       ref="funcTree"
                         node-key="id"
                       empty-text="暂无数据"
                       show-checkbox
                       class="form-tree"
                       @check="funcChecked"

                       ></el-tree>
            </el-form-item>
            </el-col>
            <el-col :span="11" :offset="2" v-if="roleForm.managerFlag === 1">
              <el-form-item label="数据授权" prop="deptIdList">
              <el-tree :data="deptTreeList"
                       :props="deptTreeProps"
                       :default-checked-keys="roleForm.deptIdList"
                       ref="deptTree"
                       node-key="id"
                       empty-text="暂无数据"
                       show-checkbox
                       class="form-tree"
                       @check="deptChecked"
                       ></el-tree>
            </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addOrUpdateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="clickConfirm">确 定</el-button>
      </div>
    </el-dialog>-->
  </div>

</template>

<script>
import BasePaging from '../../common/BasePaging'
import {isAuth} from '../../../utils'
import {
  addRole,
  getRoleList,
  updateRole,
  deleteRole,
  getFuncTreeList,
  getDeptTreeList,
  getRoleById
} from '../../../api/customer/role'
import FunctionAuthorization from './Component/FunctionAuthorization'
import DataAuthorization from './Component/DataAuthorization'
import AuthorizationForm from './Component/AuthorizationForm'

export default {
  name: 'role',
  components: {AuthorizationForm, DataAuthorization, FunctionAuthorization},
  extends: BasePaging,
  created () {
    if (isAuth('ent:role:paging')) { this.paging() }
  },
  mounted () {
    if (isAuth('ent:role:paging')) {
      this.paging()
    }
  },
  data () {
    let funcTreeValidator = (rule, value, callback) => {
      let checkedList = this.$refs.funcTree.getCheckedKeys()
      if (checkedList.length === 0 || !checkedList) {
        callback(new Error('请选择功能授权'))
      } else {
        callback()
      }
    }
    let deptTreeValidator = (rule, value, callback) => {
      let checkedList = this.$refs.deptTree.getCheckedKeys()
      if (checkedList.length === 0 || !checkedList) {
        callback(new Error('请选择数据授权'))
      } else {
        callback()
      }
    }
    return {
      // 测试状态
      testFalse: false,
      isAddRole: true,
      bodyHeight: 0,
      searchHeight: 0,
      inqerts: false,
      funcTableData: [],
      params: {
        name: ''
      },
      roleForm: {
        'id': '',
        'name': '',
        'remark': '',
        'managerFlag': 0,
        'areaManagerFlag': 0,
        'parentId': '',
        'menuIdList': [],
        'deptIdList': []
      },
      // 半选的功能项
      halfMenuIdList: [],
      labelPosition: 'right',
      addOrUpdateDialogVisible: false,
      dataListLoading: false,
      roleAsOptionList: [],
      tableData: [],
      roleList: [],
      // 表单数据校验规则
      roleFormRules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        menuIdList: [
          { required: true, validator: funcTreeValidator, trigger: 'blur' }
        ],
        deptIdList: [
          { required: true, validator: deptTreeValidator, trigger: 'blur' }
        ]
      },
      // 树控件数据
      funcTreeList: [],
      deptTreeList: [],
      // table选中行列表
      tableSelection: [],
      funcTreeProps: {
        children: 'children',
        label: 'name'
      },
      deptTreeProps: {
        children: 'children',
        label: 'label'
      },
      tempKey: -666666
    }
  },

  methods: {
    isAuth (auth) {
      return isAuth(auth)
    },
    // 获取分页
    paging () {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/ent/role/paging'),
        method: 'post',
        data: this.$http.adornData({
          'conditions': {
            'name': this.params.name
          },
          'inOrder': '',
          'orderBy': '',
          'pageNum': this.queryInfo.pageIndex,
          'pageSize': this.queryInfo.pageSize
        })
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.tableData = data.data.records
          this.totalPage = data.data.total
        } else {
          this.$message.error(data.msg)
        }
        this.dataListLoading = false
      })
    },
    // 初始化角色表单
    initRoleForm () {
      this.roleForm.name = ''
      this.roleForm.remark = ''
      this.roleForm.managerFlag = 0
      this.roleForm.parentId = ''
      this.roleForm.menuIdList = []
      this.roleForm.deptIdList = []
    },
    // 点击搜索
    clickSearch () {
      this.queryInfo.pageIndex = 1
      this.paging()
    },
    // 清空角色姓名input
    clearName () {
      this.queryInfo.pageIndex = 1
      this.paging()
    },
    // func获取选中的节点
    funcChecked (data, checkedObj) {
      this.roleForm.menuIdList = checkedObj.checkedKeys
      this.halfMenuIdList = checkedObj.halfCheckedKeys
    },
    // dept获取选中的节点
    deptChecked (data, checkedObj) {
      this.roleForm.deptIdList = checkedObj.checkedKeys
    },
    // 点击重置
    clickReset () {
      this.$refs['queryFormRef'].resetFields()
      this.paging()
    },

    // 显示新增修改对话框
    showAddOrUpdateDialog (isAdd, roleId) {
      this.getDeptTreeList()
      this.getFuncTreeList()
      this.getRoleList()
      this.isAddRole = isAdd
      if (!isAdd) {
        getRoleById(roleId,
          (data) => {
            // this.roleForm = data.data
            let idx = data.data.menuIdList.indexOf(this.tempKey)
            this.roleForm.id = data.data.id
            this.roleForm.name = data.data.name
            this.roleForm.remark = data.data.remark
            this.roleForm.managerFlag = data.data.managerFlag
            this.roleForm.areaManagerFlag = data.data.areaManagerFlag
            this.roleForm.parentId = data.data.parentId
            // this.roleForm.parentId = null
            if (idx !== -1) {
              // data.data.menuIdList.splice(idx, data.data.menuIdList.length - idx)
            }
            // this.$refs.funcTree.setCheckedKeys(data.data.menuIdList)
            this.roleForm.menuIdList = data.data.menuIdList
            this.roleForm.deptIdList = data.data.deptIdList
          })
      } else {
        this.initRoleForm()
      }
      this.addOrUpdateDialogVisible = true
    },
    // 获取角色列表
    getRoleList () {
      getRoleList((data) => { this.roleList = data.data })
    },
    // 点击新增
    clickAdd () {
      this.$refs['roleFormRefs'].validate((valid) => {
        if (valid) {
          addRole({
            'id': this.roleForm.id,
            'name': this.roleForm.name,
            'remark': this.roleForm.remark,
            'managerFlag': this.roleForm.managerFlag,
            'areaManagerFlag': this.roleForm.areaManagerFlag,
            'parentId': this.roleForm.parentId,
            // 'menuIdList': this.roleForm.menuIdList,
            'menuIdList': this.$refs.funcAuthRefs.getSelectedMenuIdList(),
            // 'deptIdList': this.roleForm.deptIdList
            'deptIdList': this.$refs.dataAuthRefs.getSelectedDataIdList()
          }, () => {
            this.addOrUpdateDialogVisible = false
            this.$message.success('添加成功!')
            this.paging()
          })
        } else {
          return false
        }
      })
    },
    // 点击修改
    clickUpdate (roleId) {
      this.$refs['roleFormRefs'].validate((valid) => {
        if (valid) {
          updateRole({
            'id': this.roleForm.id,
            'name': this.roleForm.name,
            'remark': this.roleForm.remark,
            'managerFlag': this.roleForm.managerFlag,
            'areaManagerFlag': this.roleForm.areaManagerFlag,
            'parentId': this.roleForm.parentId,
            // 'menuIdList': [].concat(this.$refs.funcTree.getCheckedKeys(), [this.tempKey], this.$refs.funcTree.getHalfCheckedKeys()),
            // 'menuIdList': this.roleForm.menuIdList,
            'menuIdList': this.$refs.funcAuthRefs.getSelectedMenuIdList(),
            // 'deptIdList': this.roleForm.deptIdList
            'deptIdList': this.$refs.dataAuthRefs.getSelectedDataIdList()
          }, () => {
            this.addOrUpdateDialogVisible = false
            this.$message.success('修改成功!')
            this.paging()
          })
        } else {
          return false
        }
      })
    },
    clickConfirm () {
      if (this.isAddRole) {
        this.clickAdd()
      } else {
        this.clickUpdate()
      }
      this.paging()
    },
    // 过滤table选择的id
    getTableSelectionIdList (selectionList = []) {
      return selectionList.map((item) => item.id)
    },
    // Table操作
    handleSelectionChange (selection) {
     // console.log('selection', selection)
      this.tableSelection = selection
    },
    // 显示删除确认对话框
    showDeleteDialog (role) {
    //  console.log('role', role)
      this.$confirm(`确认要删除角色 ${role.name} 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRole(role.id, () => { this.paging() })
      })
    },
    // 显示批量删除对话框
    showDeleteDialogBatch () {
      let selectIdList = this.getTableSelectionIdList(this.tableSelection)
      this.$confirm(`确认要批量删除吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRole(selectIdList, () => { this.paging() })
      })
    },
    // 点击删除账号
    clickDelete (role) {
      this.showDeleteDialog(role)
    },
    // 批量删除
    clickDeleteBatch () {
      this.showDeleteDialogBatch()
    },
    // 获取部门列表信息
    getDeptTreeList () {
      getDeptTreeList({}, (data) => { this.deptTreeList = data.deptInfo.children })
    },
    // 获取功能列表信息
    getFuncTreeList () {
      getFuncTreeList({}, (data) => { this.funcTreeList = data.data; this.transformMenuTreeToList() })
    },
    transformMenuTreeToList () {
      // let menuTree = this.funcTreeList
      // let menuList = []

     // console.log('menuTree', menuTree)
    },
    nodeTransformer (node) {
    }
/*    getMenuIdList (val) {
      console.log('menuVal', val)
      this.roleForm.menuIdList = this.$refs.funcAuthRefs.getSelectedMenuIdList()
    }, */
/*    getDataIdList (val) {
      console.log('dataVal', val)
      this.roleForm.deptIdList = val
    } */
  }
}
</script>

<style lang='less'>
.el-popover.popper-style {
  min-width: 50px !important;
}

.el-popper.popper-style {
  margin-top: 0;
}

.btn-text-danger {
  color: #E96E6E;
}

.btn-text-normal {
  color: #6E92E9;
}

.form-tree {
  height: 220px;
  overflow: auto;
}
</style>
